package com.mx.zb.mng.utils;

import com.qiniu.util.Auth;  
import java.io.IOException;

import com.google.gson.Gson;
import com.qiniu.common.QiniuException;
import com.qiniu.common.Zone;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;  
  
public class QiniuUtil {  
      
    /**基本配置-从七牛管理后台拿到*/  
  //设置好账号的ACCESS_KEY和SECRET_KEY  
  String ACCESS_KEY = "_WXEvsGC2_eokbBnAF2PbItB8S_20-hB8wCgsTIj";  
  String SECRET_KEY = "uszpUPK6z_5OuVkkcdS1ilg68bqPqSkXVXBlIsdB";
  public static final String Qiniu_url ="http://img.1miaodao.cn/";
//对应要上传到七牛上 你的那个路径（自己建文件夹 注意设置公开）   
  String bucketname = "miaodao";  
  //上传到七牛后保存的文件名---不指定的话，七牛随机产生-无后缀  
  String key = null;  
  //上传文件的路径  
//  String FilePath = "f:\\0.png";  //本地要上传文件路径  
  //密钥配置  
  Auth auth = Auth.create(ACCESS_KEY, SECRET_KEY);  
  Configuration cfg = new Configuration(Zone.zone0());
  //创建上传对象  
  UploadManager uploadManager = new UploadManager(cfg);  
  //简单上传，使用默认策略，只需要设置上传的空间名就可以了  
  public String getUpToken(){  
      return auth.uploadToken(bucketname);  
  }  
  
  public String upload(String FilePath) throws IOException{  
    try {  
      //调用put方法上传  
      Response res = uploadManager.put(FilePath, key, getUpToken());  
      //解析上传成功的结果
      DefaultPutRet putRet = new Gson().fromJson(res.bodyString(), DefaultPutRet.class);
      System.out.println(putRet.key);
      System.out.println(putRet.hash);
      //打印返回的信息  
      System.out.println(res.bodyString());   
      return putRet.key;
      } catch (QiniuException e) {  
          Response r = e.response;  
          // 请求失败时打印的异常的信息  
          System.out.println(r.toString());  
          try {  
              //响应的文本信息  
            System.out.println(r.bodyString());  
          } catch (QiniuException e1) {  
              //ignore  
          }  
      }
	return "error";    
        
  }  
  
  public static void main(String args[]) throws IOException{    
	  String FilePath = "f:\\0.png";  //本地要上传文件路径  
    new QiniuUtil().upload(FilePath);  
  }  
  
}  